#include "mainwidget.h"
#include "ui_mainwidget.h"

mainwidget::mainwidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::mainwidget)
{
    ui->setupUi(this);
    QPalette plt;
    plt.setColor(QPalette::Window,QColor(80,200,130));
    setPalette(plt);

    connectMySQLDatabaseFunc();
    setWindowFlags(windowFlags()&~Qt::WindowMaximizeButtonHint);
    setFixedSize(this->width(),this->height());

    addTableWidgetHeaderFunc();

}

mainwidget::~mainwidget()
{
    delete ui;
}
//连接数据库
void mainwidget::connectMySQLDatabaseFunc()
{
    QSqlDatabase database = QSqlDatabase::addDatabase("QMYSQL");
    database.setHostName("localhost");
    database.setPassword("root");
    database.setUserName("root");
    database.setPort(3306);
    database.setDatabaseName("stockdatabase");
    if(!database.open())
    {
        QMessageBox::information(this,"警告","数据库连接失败！！！",QMessageBox::Yes);
    }
}
//商品添加
void mainwidget::on_pushButton_GoodsAdd_clicked()
{
    addgoods *w = new addgoods;
    w->setAttribute(Qt::WA_DeleteOnClose); // 设置窗口关闭时自动释放内存
    w->show();



}
//删除商品
void mainwidget::on_pushButton_GoodsDelete_clicked()
{
    int iClick = QMessageBox::warning(this,"警告","警告：删除操作是根据商品编号进行删除，是否确认删除？",QMessageBox::Yes|QMessageBox::No);
    if(iClick == QMessageBox::Yes)
    {
        int iRow = ui->tableWidget_ListData->currentRow();
        QString value = ui->tableWidget_ListData->model()->index(iRow,0).data().toString();
        if(!value.isEmpty())
        {
            QMessageBox::critical(this,"错误","删除商品必须要选择编号，请重新选择！",QMessageBox::Yes);
            return;
        }
        QSqlQuery sqlquery;

        int goodsid = value.toInt();
        sqlquery.prepare("DELETE FROM stock_info WHERE stockid =:value");
        sqlquery.bindValue(":value",goodsid);

        if(sqlquery.exec())
        {
            QMessageBox::information(this,"提示","删除成功",QMessageBox::Yes);
        }
    }
}
//商品入库
void mainwidget::on_pushButton_GoodsWarehousing_clicked()
{
    warehousing *ware = new warehousing;
    ware->setAttribute(Qt::WA_DeleteOnClose);
    ware->show();


}
//商品出库
void mainwidget::on_pushButton_GoodsDelivery_clicked()
{
    delivery *d = new delivery;
    d->setAttribute(Qt::WA_DeleteOnClose);
    d->show();
}
void mainwidget::on_pushButton_ExportData_clicked()
{
    QDateTime time = QDateTime::currentDateTime();
    QString strTemp = time.toString("yyyy-MM-dd hhmmss");

    QString strFileName = QFileDialog::getSaveFileName(this, tr("Excel Files"), QString("./%1%2").arg(strTemp).arg("_kcgl"), tr("Excel Files (*.xls)"));
    if (!strFileName.isEmpty())
    {
        QAxObject *excel = new QAxObject("Excel.Application");
        excel->setProperty("Visible", false);
        excel->setProperty("DisplayAlerts", false);

        QAxObject *workbooks = excel->querySubObject("Workbooks");
        workbooks->dynamicCall("Add");
        QAxObject *workbook = excel->querySubObject("ActiveWorkBook");
        QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1);
        QAxObject *cell;

        // 写入表头
        for (int i = 0; i < ui->tableWidget_ListData->columnCount(); i++)
        {
            cell = worksheet->querySubObject("Cells(int,int)", 1, i + 1);
            cell->dynamicCall("SetValue(const QString&)", ui->tableWidget_ListData->horizontalHeaderItem(i)->text());
            cell->setProperty("RowHeight", 38);
        }

        // 写入数据
        for (int row = 0; row < ui->tableWidget_ListData->rowCount(); row++)
        {
            for (int col = 0; col < ui->tableWidget_ListData->columnCount(); col++)
            {
                cell = worksheet->querySubObject("Cells(int,int)", row + 2, col + 1);
                cell->dynamicCall("SetValue(const QString&)", ui->tableWidget_ListData->item(row, col)->text());
            }
        }

        workbook->dynamicCall("SaveAs(const QString&)", QDir::toNativeSeparators(strFileName));
        workbook->dynamicCall("Close()");
        excel->dynamicCall("Quit()");

        delete excel;
    }
}

//商品汇总
void mainwidget::on_pushButton_RollupData_clicked()
{
    datasum *data = new datasum;
    data->setAttribute(Qt::WA_DeleteOnClose);
    data->show();
}

void mainwidget::on_pushButton__DataSearch_clicked() //查询
{
    QSqlQuery sqlQuery;
    QString searchNumber = ui->lineEdit_GoodsNumber->text();
    sqlQuery.prepare("SELECT * FROM stock_info WHERE stockid = :stockid");
    sqlQuery.bindValue(":stockid", searchNumber.toInt());

    if (sqlQuery.exec())
    {
        int rowCount = 0;
        while (sqlQuery.next()) // 循环处理每一行结果
        {
            ui->tableWidget_ListData->setRowCount(rowCount + 1); // 增加行数
            for (int i = 0; i < 9; ++i)
            {
                QTableWidgetItem *item = new QTableWidgetItem(sqlQuery.value(i).toString());
                ui->tableWidget_ListData->setItem(rowCount, i, item); // 使用正确的行号
            }
            rowCount++; // 增加行号
        }
    }
    else
    {
        qDebug() << "Query execution error:" << sqlQuery.lastError().text();
    }
}

void mainwidget::addTableWidgetHeaderFunc()
{
    QSqlQuery sqlQuery;
        QString sql = QString("SELECT * FROM stock_info");
        if(!sqlQuery.exec(sql))
        {
            qDebug() << "执行SQL查询时出错:" << sqlQuery.lastError().text();
            return;
        }

        ui->tableWidget_ListData->setColumnCount(9);
        ui->tableWidget_ListData->setHorizontalHeaderLabels(QStringList()<<"编号"<<"名称"<<"数量"<<"单价"<<"供应商家"<<"负责人"<<"入库时间"<<"出库时间"<<"备注");

        int rowCount = 0;
        while(sqlQuery.next())
        {
            ui->tableWidget_ListData->setRowCount(rowCount + 1);
            for(int i = 0; i < 9; i++)
            {
                QTableWidgetItem *item = new QTableWidgetItem(sqlQuery.value(i).toString());
                ui->tableWidget_ListData->setItem(rowCount, i, item);
            }
            rowCount++;
        }

        // 设置列宽度
        ui->tableWidget_ListData->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);

}







void mainwidget::on_pushButton_RollupData_2_clicked()
{
    QSqlQuery sqlQuery;
    QString sql = QString("SELECT * FROM stock_info");
    if(!sqlQuery.exec(sql))
    {
        qDebug() << "执行SQL查询时出错:" << sqlQuery.lastError().text();
        return;
    }

    ui->tableWidget_ListData->clear(); // 清空表格数据
    ui->tableWidget_ListData->setRowCount(0); // 重置行数

    ui->tableWidget_ListData->setColumnCount(9);
    ui->tableWidget_ListData->setHorizontalHeaderLabels(QStringList()<<"编号"<<"名称"<<"数量"<<"单价"<<"供应商家"<<"负责人"<<"入库时间"<<"出库时间"<<"备注");

    int rowCount = 0;
    while(sqlQuery.next())
    {
        ui->tableWidget_ListData->insertRow(rowCount); // 插入新行
        for(int i = 0; i < 9; i++)
        {
            QTableWidgetItem *item = new QTableWidgetItem(sqlQuery.value(i).toString());
            ui->tableWidget_ListData->setItem(rowCount, i, item);
        }
        rowCount++;
    }

    // 设置列宽度
    ui->tableWidget_ListData->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
}
